<template>
    <ContentWrap v-loading="formLoading">
        <el-form ref="formRef" :model="formData" label-width="140px" label-suffix="：" :rules="rules" class="w-60%">
            <el-form-item label="负责人" prop="storeLeader">
                <el-select v-model="formData.storeLeader" placeholder="请选择负责人" :disabled="isDetail">
                    <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id + ''" />
                </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
                <el-input v-model="formData.phone" :maxlength="11" placeholder="请输入联系电话" :disabled="isDetail" />
            </el-form-item>
            <el-form-item label="门店名称" prop="storeName">
                <el-input v-model="formData.storeName" :maxlength="50" placeholder="请输入门店名称" :disabled="isDetail" />
            </el-form-item>
            <el-form-item label="到期时间" prop="expirationTime">
                <el-date-picker
                    v-model="formData.expirationTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="选择到期时间"
                    class="!w-100%"
                    align="center"
                    :popper-options="{
                         modifiers: [
                            {
                                name: 'flip',
                                options: {
                                    fallbackPlacements: ['bottom'],
                                    allowedAutoPlacements: ['bottom'],
                                }
                            }
                        ]
                    }"
                />
            </el-form-item>
            <el-form-item label="营业开始时间" prop="openingTime">
                <el-time-select
                v-model="formData.openingTime"
                start="00:00"
                step="00:10"
                end="23:59"
                placeholder="选择时间"
                @change="changeTime"
                :disabled="isDetail" />
            </el-form-item>
            <el-form-item label="营业结束时间" prop="closingTime">
                <el-time-select
                v-model="formData.closingTime"
                :start="formData.openingTime || '00:00'"
                step="00:10"
                end="23:59"
                placeholder="选择时间"
                :disabled="isDetail" />
            </el-form-item>
            <el-form-item label="营业天数" prop="jobDays">
                <el-select v-model="formData.jobDays" multiple placeholder="请选择营业天数">
                    <el-option label="周一" value="周一" />
                    <el-option label="周二" value="周二" />
                    <el-option label="周三" value="周三" />
                    <el-option label="周四" value="周四" />
                    <el-option label="周五" value="周五" />
                    <el-option label="周六" value="周六" />
                    <el-option label="周日" value="周日" />
                </el-select>
            </el-form-item>
            <el-form-item label="商户号" prop="storeCode">
                <el-input v-model="formData.storeCode" placeholder="请输入商户号" :disabled="isDetail" />
            </el-form-item>
            <!-- <el-form-item label="管理员" prop="storeAdmin"> -->
                <!-- <el-select v-model="formData.storeAdmin" multiple placeholder="请选择管理员">
                    <el-option v-form="item, index in leaderList" :key="index" :label="item.name" :value="item.id" />
                </el-select> -->
            <!-- </el-form-item> -->
            <el-form-item label="开团区县" prop="areaCode">
                <el-select v-model="formData.areaCode" multiple placeholder="请选择开团区县" :disabled="isDetail">
                    <el-option v-for="item in areaList1" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
            </el-form-item>
            <el-form-item label="费率" prop="premiumRate">
                <el-input-number v-model="formData.premiumRate" :controls="false" :precision="2" />
            </el-form-item>
            <el-form-item label="所在地区" prop="areaId">
                <!-- <el-cascader class="w-100%" filterable v-model="formData.areaId" :options="areaList" :props="{ label: 'name', value: 'id' }" :show-all-levels="false" /> -->
                <el-select v-model="formData.areaId" placeholder="请选择所在地区" :disabled="isDetail">
                    <el-option v-for="item in areaList1" :key="item.id" :label="item.name" :value="item.id as number" />
                </el-select>
            </el-form-item>
            <el-form-item label="详细地址" prop="detailAddress">
                <el-input v-model="formData.detailAddress" readonly placeholder="请点击选择门店地址" @click="handleSelectAddress" />
            </el-form-item>
            <el-form-item label="重要提示" prop="importantInfo">
                <el-input type="textarea" :rows="4" v-model="formData.importantInfo" :maxlength="300" show-word-limit placeholder="请输入重要提示" :disabled="isDetail" />
            </el-form-item>
            <el-form-item label="门店logo" prop="logo">
                <UploadImg v-model="formData.logo" :disabled="isDetail" height="80px" />
            </el-form-item>
            <el-form-item label="二维码" prop="qrCode">
                <UploadImg v-model="formData.qrCode" :disabled="isDetail" height="80px" />
            </el-form-item>
            <el-form-item label="门店图片" prop="storePicUrls">
                <UploadImg v-model="formData.storePicUrls" :disabled="isDetail" height="80px" />
            </el-form-item>
            <el-form-item label="门店海报" prop="storePoster">
                <UploadImg v-model="formData.storePoster" :disabled="isDetail" height="80px" />
            </el-form-item>
            <el-form-item label="身份证正面" prop="leaderIdcardUrl1">
                <UploadImg v-model="formData.leaderIdcardUrl1" :disabled="isDetail" height="80px" />
            </el-form-item>
            <el-form-item label="身份证反面" prop="leaderIdcardUrl2">
                <UploadImg v-model="formData.leaderIdcardUrl2" :disabled="isDetail" height="80px" />
            </el-form-item>
            <!-- <el-form-item label="详细地址" prop="detailAddress">
                <el-input v-model="formData.detailAddress" placeholder="请输入详细地址" :disabled="isDetail" />
            </el-form-item> -->
            <el-form-item label="">
                <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
                    保存
                </el-button>
                <el-button @click="close">返回</el-button>
            </el-form-item>
        </el-form>
        <el-dialog v-model="showAddressSelect" title="地址选择" width="60%" :close-on-click-modal="false">
            <iframe id="mapPage" width="100%" height="600px" frameborder=0
                src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=JXWBZ-2CX34-OPOU2-DECPC-PN47J-57BQI&referer=javascript_map">
            </iframe>
        </el-dialog>
    </ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as StoreApi from '@/api/system/store'
import * as AreaApi from '@/api/system/area'
import * as UserApi from '@/api/system/user'
import { convertToInteger, floatToFixed2, formatToFraction } from '@/utils'
import request from '@/config/axios'

defineOptions({ name: 'StoreForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { params, name } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('info') // Tag 激活的窗口
const isDetail = ref(false) // 是否查看详情
const formRef = ref();
const showAddressSelect = ref(false) // 地址选择弹窗
// 表单数据
const formData = ref<StoreApi.Store>({
    storeLeader: '', // 负责人
    phone: '', // 联系电话
    storeName: '', // 门店名称
    openingTime: '', // 营业开始时间
    closingTime: '', // 营业结束时间
    jobDays: [], // 营业天数
    storeCode: '', // 商户号
    storeAdmin: [], // 管理员
    areaCode: [], // 开团区县
    premiumRate: '', // 费率
    areaId: undefined, // 所在地区
    detailAddress: '', // 门店详细地址
    importantInfo: '', // 重要提示
    logo: '', // logo
    qrCode: '', // 二维码
    storePicUrls: '', // 门店图片
    storePoster: '', // 门店海报
    leaderIdcardUrl: [], // 管理员身份证
    leaderIdcardUrl1: '', // 身份证正面 - 临时字段
    leaderIdcardUrl2: '', // 身份证反面 - 临时字段
    expirationTime: '', // 到期时间
    latitude: undefined, // 纬度
    longitude: undefined, // 经度
    status: 1, // 门店状态
})
const rules = reactive({
    storeLeader: [required],
    phone: [{
      required,
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }],
    storeName: [required],
    openingTime: [required],
    closingTime: [required],
    jobDays: [required],
    storeCode: [required],
    // storeAdmin: [required],
    areaCode: [required],
    premiumRate: [required],
    areaId: [required],
    detailAddress: [required],
    logo: [required],
    qrCode: [required],
    storePicUrls: [required],
    storePoster: [required],
    leaderIdcardUrl1: [required],
    leaderIdcardUrl2: [required],
    expirationTime: [required],
})

/**
 * 到期时间控件配置
 */
const pickerOptionsRang = (time) => {
    return time.getTime() < Date.now() - 8.64e7; // 8.64e7 毫秒数代表一天
};

/** 查询地区 */
const areaList = ref([]);
const areaList1 = ref([]);
const getAreaTree = async () => {
    const res = await AreaApi.getAreaTree();

    areaList.value = res;
    let data = res.filter(item => item.name == '湖南省')[0];

    if (data) {
        data = data.children.filter(item => item.name == '长沙市')[0];

        if (data) {
            areaList1.value = data.children;
        }
    }
}

/** 查询管理员 */
const userList = ref([]);
const getUserList = async () => {
    try {
        const res = (await UserApi.getSimpleUserList()) as UserApi.UserVO
        userList.value = res.filter(item => item.id !== 1);
    } finally {
        
    }
}

/** 获得详情 */
const getDetail = async () => {
    if ('StoreDetail' === name) {
        isDetail.value = true
    }
    const id = params.id as unknown as number
    if (id) {
        formLoading.value = true
        try {
            const res = (await StoreApi.getStoreDetail(id)) as StoreApi.Store
            formData.value = res
        } finally {
            formLoading.value = false
        }
    }
}


const getLocation = (event) => {
    // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
    var loc = event.data;
    // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
    if (loc && loc.module == 'locationPicker') {
        showAddressSelect.value = false;
        formData.value.detailAddress = loc.poiaddress;
        formData.value.latitude = loc.latlng.lat;
        formData.value.longitude = loc.latlng.lng;
    }
}

const handleSelectAddress = () => {
    showAddressSelect.value = true;
}

const changeTime = () => {
    formData.value.closingTime = '';
}

/** 提交按钮 */
const submitForm = async () => {
    // 提交请求
    formLoading.value = true
    try {

        // getLocation();
        // 校验各表单
        await unref(formRef)?.validate()

        const deepCopyFormData = cloneDeep(unref(formData.value)) as StoreApi.Store

        deepCopyFormData.leaderIdcardUrl = [deepCopyFormData.leaderIdcardUrl1, deepCopyFormData.leaderIdcardUrl2]

        // 校验都通过后提交表单
        const data = deepCopyFormData as StoreApi.Store
        const id = params.id as unknown as number


        if (!id) {
            await StoreApi.createStore(data)
            message.success(t('common.createSuccess'))
        } else {
            await StoreApi.updateStore(data)
            message.success(t('common.updateSuccess'))
        }
        close()
    } finally {
        formLoading.value = false
    }
}

/** 关闭按钮 */
const close = () => {
    delView(unref(currentRoute))
    push({ name: 'SystemStore' })
}

/** 初始化 */
onMounted(async () => {
    getAreaTree();
    getUserList();
    await getDetail()

    window.addEventListener('message', getLocation, false);
})

onUnmounted(() => {
    window.removeEventListener('message', getLocation, false);
})
</script>
